package com.pi.shisan.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pi.shisan.service.domain.MyWeatherCity;
import com.pi.shisan.service.domain.WeatherCity;
import com.pi.shisan.service.dto.CityDTO;
import com.pi.shisan.service.mapper.MyWeatherCityMapper;
import com.pi.shisan.service.mapper.WeatherCityMapper;
import com.pi.shisan.service.service.CityService;
import com.pi.shisan.service.service.WeatherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private MyWeatherCityMapper myWeatherCityMapper;

    @Autowired
    private WeatherCityMapper weatherCityMapper;

    @Autowired
    private WeatherService weatherService;

    @Override
    public synchronized void setMyCity(Long id) throws Exception{
        Long old = myWeatherCityMapper.selectMyCityRecordId();
        if (Objects.equals(old, id)) {
            return;
        }
        myWeatherCityMapper.clear();
        MyWeatherCity myWeatherCity = new MyWeatherCity();
        myWeatherCity.setCityRecordId(id);
        myWeatherCityMapper.insert(myWeatherCity);
        weatherService.forceGetWeatherInfo();
    }

    @Override
    public List<CityDTO> getCityList(Long pid) {
        if (pid == null) {
            pid = 0L;
        }
        List<WeatherCity> list = weatherCityMapper.selectList(
                new LambdaQueryWrapper<WeatherCity>()
                        .eq(WeatherCity::getPid, pid)
        );
        if (list == null || list.isEmpty()) {
            return null;
        }
        List<CityDTO> citys = new ArrayList<>(list.size());
        for (WeatherCity c : list) {
            CityDTO cityDTO = new CityDTO();
            BeanUtils.copyProperties(c, cityDTO);
            citys.add(cityDTO);
        }
        return citys;
    }
}
